'use strict';
module.exports = {
	/**
	 * XXXnameXXX
	 * @url client/user/pub/proportional_callabck 前端调用的url参数地址
	 * data 请求参数
	 * @param {String} params1  参数1
	 */
	main: async (event) => {
		let {
			data = {}, userInfo, util, filterResponse, originalParam
		} = event;
		let {
			customUtil,
			uniID,
			config,
			pubFun,
			vk,
			db,
			_
		} = util;
		let {
			uid,
			out_trade_no, //充值订单号
			total_fee, //支付金额
			_add_time,
			_add_time_str,
			percent,
		} = data;
		let res = {
			code: 0,
			msg: ""
		};
		// 业务逻辑开始-----------------------------------------------------------

		await db.collection('vk-test').add({
			tips: "执行了比例回传函数proportional_callabck",
			request_id: event.originalParam.context.requestId,
			out_trade_no: out_trade_no
		})
		let orderinfo = await db.collection('a_recharge').where({
			out_trade_no: out_trade_no
		}).get()

		console.log("回传参数percent", percent);



		// 从代理商获取
		let douyinRadio = 1; //抖音回传模式  默认为百分比
		let douyin_ReturnRatio = percent.data[0].douyin_ReturnRatio || 0; //抖音上传比例
		let douyin_UnReturnRatio = percent.data[0].douyin_UnReturnRatio || 0; //抖音不上传比例
		let douyinMaxPrice = percent.data[0].douyinMaxPrice || 0;
		let douyinMinPrice = percent.data[0].douyinMinPrice || 0;
		let firstorder = percent.data[0].firstorder;
		let hour_backhaul = percent.data[0].hour_backhaul || 24;
		let newuser = percent.data[0].newuser;

		let radionum = percent.data[0].amountRanges.radio || 1

		console.log("newusernewusernewusernewuser", newuser);

		//获取今日开始时间戳
		let {
			yesterdayStart,
			todayStart,
			todayEnd
		} = vk.pubfn.getCommonTime(new Date());



		if (newuser === 0) {
			newuser = false

		} else {
			newuser = true
		}

		console.log("newuser=========", newuser);

		let newsday = newuser ? todayStart : new Date().getTime() - 3600000 * hour_backhaul;

		var OrderNum = 0;
		//获取代理商旗下订单总条数
		let minTotal = douyinMinPrice * 100;
		let maxTotal = douyinMaxPrice * 100;
		let ReturnRatio = douyin_ReturnRatio;
		let UnReturnRatio = douyin_UnReturnRatio;

		console.log("minTotal", minTotal);
		console.log("maxTotal", maxTotal);
		console.log("ReturnRatio", ReturnRatio);
		console.log("UnReturnRatio", UnReturnRatio);

		// 查询用户用户支付次数
		let recharge_all = await vk.baseDao.count({
			dbName: "a_recharge", // 表名
			whereJson: { // 条件
				pay_status: 1,
				user_id: orderinfo.data[0].user_id,
			}
		});
		console.log("支付次数==========", recharge_all);

		console.log("total_fee", total_fee);
		console.log("maxTotal======", maxTotal);

		// 已支付 付款金额在区间内
		if (orderinfo.data[0].pay_status === 1 &&& radionum == 3) {
			console.log("newsday", newsday);

			console.log("orderinfo.data[0].user_register_date===", orderinfo.data[0].user_register_date);
			//   是否首单  注册时间是今日  付款笔数是否 是 1
			if (firstorder && orderinfo.data[0].user_register_date >= newsday && recharge_all === 1) {
				OrderNum = await updateProportionValue(percent, orderinfo.data[0].tfid);
				console.log("OrderNum111", OrderNum);
			} else if (!firstorder && orderinfo.data[0].user_register_date >= newsday) {
				OrderNum = await updateProportionValue(percent, orderinfo.data[0].tfid);
				console.log("OrderNum222", OrderNum);
			}

			console.log("total_fee", OrderNum);
		}

		//更新比例数值函数
		async function updateProportionValue(percent, tfid) {
			console.log("tfid", tfid);
			try {

				var proportion_value = percent.data[0].proportion_value || 0;
				proportion_value = proportion_value + 1;
				console.log("proportion_value", proportion_value);
				console.log("tfid222222222222222222222", tfid);
				if (tfid) {
					console.log("3333333333333333333", tfid);
					await db.collection('a_config').where({
						name: "RebackPercent",
						tfid: tfid
					}).update({
						proportion_value: _.inc(1)
					});
				}
				return proportion_value;
			} catch (err) {
				console.log("比例数值错误");
			}
		}

		//计算是否回传
		let RatioSum = Number(ReturnRatio) + Number(UnReturnRatio) //比例之和
		console.log("RatioSum", RatioSum);
		console.log("OrderNum", OrderNum);
		if ((OrderNum % RatioSum) <= Number(ReturnRatio) && (OrderNum % RatioSum) > 0) {
			// 云函数内调用其他云函数或云对象内的函数,进行付费数据回传。
			let callRes = await vk.callFunction({
				name: "hedian",
				url: 'client/user/pub/callback',
				data: {
					out_trade_no: out_trade_no, //充值订单号
					total_fee: total_fee, //支付金额
					_add_time: data._add_time,
					_add_time_str: data._add_time_str
				},
			});
			console.log(callRes)
			console.log("douyin")
			await addvktest("循环回传");

		} else {
			console.log("循环回传但不回传")
			await addvktest("循环回传但不回传");
		}


		// 业务逻辑结束-----------------------------------------------------------
		return res;

		async function addvktest(tips) {
			let addvktest = await db.collection('vk-test').add({
				tips: tips,
				out_trade_no: out_trade_no,
				total_fee: total_fee,
				_add_time: _add_time,
				_add_time_str: _add_time_str
			})
		}
	}
}